package com.mobilesales.android.adapters;

import java.util.List;

import com.mobilesales.android.R;
import com.mobilesales.android.model.tasks.CyclicTask;
import com.mobilesales.android.model.tasks.Task;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TaskArrayAdapter extends ArrayAdapter<Task> {

	List<Task> tasks;
	
	public TaskArrayAdapter(Context context, int textViewResourceId,
			List<Task> objects) {
		super(context, textViewResourceId, objects);
		tasks = objects;
	}
	
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.task_list_item, null);
            }
            
            Task task = null;
            if (position >= 0 && position < tasks.size()) {
            	task = tasks.get(position);
            }
            
            if (task != null) {
            	boolean isCyclicTask = (task instanceof CyclicTask);
            	String taskType = task.TaskType.Name;
            	String taskInfo = task.Info;
            	String taskStatus = task.TaskStatus.Name;
            	String timespan = String.format("%s - %s", task.StartTime.split(" ")[1],
            			task.EndTime.split(" ")[1]);
				  
            	((TextView)v.findViewById(R.id.taskType)).setText(taskType);
            	TextView taskInfoField = ((TextView)v.findViewById(R.id.taskInfo));
            	if (taskInfo==null || taskInfo.equals(""))
            		taskInfoField.setVisibility(View.GONE);
            	else
            		taskInfoField.setText(taskInfo);
            	
            	taskStatus = String.format("%s: %s", getContext().getString(R.string.Status), taskStatus);
            	((TextView)v.findViewById(R.id.taskStatus)).setText(taskStatus);
            	((TextView)v.findViewById(R.id.taskTimeSpan)).setText(timespan);
            	ImageView icon = (ImageView)v.findViewById(R.id.taskIcon);
            	icon.setImageResource(isCyclicTask ? R.drawable.cyclic_task_icon  : R.drawable.task_icon);
            }
            return v;
    }	

}
